// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
	async goodslistAction(){
		let page = this.post();
		let pages = page.pages;
		let limits = page.limits;
		let search = page.search;
		let zt = page.zt;
		let shopid = this.shop_userinfo.departmentid;

		let data = await this.model('or_shop_goods')
				.alias('sg')
				.field('sg.*, g.name, g.number, g.remarks, b.name as bname, sc.name as cname, g.isdisabled as gisdisabled')
				.join('think_or_goods g on g.id=sg.goodsid')
				.join('think_or_brand b on b.id=g.brandid')
				.join('think_or_subjectcategory sc on sc.id=g.categoryid')
				.where({'sg.shopid': shopid, 'sg.isshop': 0, 'sg.isdisable':zt, 'g.name|g.number':['like','%'+search+'%']})
				.page(pages, limits)
				.order('sg.id DESC')
				.countSelect();

		return this.json(data);
	}

	// 启用或停用产品
	async unstopAction(){
		let id = this.post('id');
		let status = this.post('status');

		let res = await this.model('or_shop_goods').where({id:id}).update({isdisable:status});
		
		if (status*1) {
			return res?this.success('弃用成功'):this.fail('弃用失败');
		} else {
			return res?this.success('启用成功'):this.fail('启用失败');
		}
	}

	// 获取机构产品品牌分类列表
	async getbrandsAction(){
		let shopid = this.shop_userinfo.departmentid;

		let orid = await this.model('or_department').where({id: shopid}).getField('pid',true);

		let data = await this.model('or_brand').where({departmentid: orid}).select();

		return this.json(data);
	}

	// 通过机构品牌获取品牌下的产品
	async querygoodsAction(){
		let cates = JSON.parse(this.post('cates'));

		let shopid = this.shop_userinfo.departmentid;

		let orid = await this.model('or_department').where({id: shopid}).getField('pid',true);

		if (think.isEmpty(cates)) cates = [0];

		let list = await this.model('or_goods').where({departmentid: orid, brandid: ['IN', cates], isdisabled:0}).select();

		let exist = await this.model('or_shop_goods').where({shopid: shopid}).getField('goodsid');

		let data = {
			glist : list,
			exist : exist
		}
		return this.json(data);
	}

	// pull organization goods to shop
	async pullgoodsAction(){

		let data = JSON.parse(this.post('data'));

		let orgoods = [];

		data.forEach((v)=>{
			orgoods.push(v.goodsid);
		})

		let shopid = this.shop_userinfo.departmentid;

		let orid = await this.model('or_department').where({id: shopid}).getField('pid',true);

		let shop_gids = await this.model('or_shop_goods').where({shopid: shopid}).getField('goodsid');

		shop_gids.forEach((v)=>{
			if (orgoods.indexOf(v) !== -1) return this.fail('拉取的产品已经存在');
		})

		let model = this.model('or_shop_goods');

		await model.transaction(async ()=>{

			try {

				let add_data = [], rednums = 1;

				for (var i = data.length - 1; i >= 0; i--) {

					add_data.push({
						goodsid: data[i].id,
						shopid: shopid,
						price: data[i].price,
						nums: data[i].nums,
						tdtype: data[i].tdtype,
						percent: data[i].percent,
						fixed: data[i].fixed,
						khtdtype: data[i].khtdtype,
						khpercent: data[i].khpercent,
						khfixed: data[i].khfixed
					})
					
				}

				let add_goods = await model.addMany(add_data);

				if (!add_goods) {
					await model.rollback();
					return this.fail('添加到分店失败');
				}

				await model.commit();
				return this.success('拉取成功');
			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('拉取失败');
			}


		})
	}

	// edit shop goods
	async editgoodsAction(){
		let goods = this.post();

		let geng = {
			price: goods.price,
			tdtype: goods.tdtype,
			percent: Number(goods.percent/100).toFixed(2),
			fixed: goods.fixed,
			khtdtype: goods.khtdtype,
			khpercent: Number(goods.khpercent/100).toFixed(2),
			khfixed: goods.khfixed
		}

		let res = await this.model('or_shop_goods').where({id: goods.id}).update(geng);

		return res?this.success('更改成功'):this.fail('更改失败');
	}




	// 添加/编辑自营产品
	async addeditAction(){
		let data = this.post();
		let shopid = this.shop_userinfo.departmentid;
		let departmentid = await this.model('or_department').where({id: shopid}).getField('pid', true)
		let addtime = Math.round(new Date().valueOf()/1000);
		
		// 判断产品名称是否重复
		let repeat = await this.model('or_goods').where('departmentid="'+departmentid+'" AND (name="'+data.name+'" OR number="'+data.number+'") AND id!="'+data.id+'"').select();

		if (!think.isEmpty(repeat)) {
			return this.fail('名称或编号重复');
		}

		if (data.tdtype==1) {
			data.percent = Number(data.percent/100).toFixed(2);
			data.fixed = 0;
		} else {
			data.percent = 0;
			data.fixed = data.fixed;
		}

		if (data.khtdtype==1) {
			data.khpercent = Number(data.khpercent/100).toFixed(2);
			data.khfixed = 0;
		} else {
			data.khpercent = 0;
			data.khfixed = data.khfixed;
		}

		if (data.id*1) {
			let upd = await this.model('or_goods').update(data);
			let shopData = {
				price: data.price,
				tdtype: data.tdtype,
				percent: data.percent,
				fixed: data.fixed,
				khtdtype: data.khtdtype,
				khpercent: data.khpercent,
				khfixed: data.khfixed,
			}
			let resShop = await this.model('or_shop_goods').where({goodsid: data.id, shopid: shopid}).update(shopData)
			return resShop?this.success('编辑成功'):this.fail('编辑失败');
		}

		let add = {
			name : data.name,
			price : data.price,
			remarks : data.remarks,
			departmentid : departmentid,
			shopid : shopid,
			addtime : addtime,
			brandid : data.brandid,
			categoryid: data.categoryid,
			nums: 0, // 机构数量为零
			number: data.number,
			tdtype: data.tdtype,
			percent: data.percent,
			fixed: data.fixed,
			khtdtype: data.khtdtype,
			khpercent: data.khpercent,
			khfixed: data.khfixed,
		}

		let res = await this.model('or_goods').add(add);

		// 加入分店产品
		let shopData = {
			goodsid: res,
			shopid: shopid,
			price: data.price,
			nums: data.nums,
			tdtype: data.tdtype,
			percent: data.percent,
			fixed: data.fixed,
			khtdtype: data.khtdtype,
			khpercent: data.khpercent,
			khfixed: data.khfixed,
			isshop: 1
		}

		let resShop = await this.model('or_shop_goods').add(shopData)
		
		return resShop ? this.success('添加成功') : this.fail('添加失败');
	}

	// 自营产品列表
	async productlistAction(){
		let page = this.get();
		let pages = page.pages;
		let limits = page.limits;
		let search = page.search;
		let zt = page.zt;
		let shopid = this.shop_userinfo.departmentid;

		let data = await this.model('or_shop_goods')
				.alias('sg')
				.field('sg.*, g.id, g.name, g.number, g.remarks, g.addtime, b.name as bname,c.name as cname')
				.join('`think_or_goods` g on g.id=sg.goodsid')
				.join('`think_or_brand` b on b.id=g.brandid')
				.join('`think_or_subjectcategory` c on c.id=g.categoryid')
				.page(pages, limits)
				.order('g.id DESC')
				.where({'sg.shopid':shopid, 'sg.isshop': 1, 'sg.isdisable':zt, 'g.name|g.number':['like','%'+search+'%']})
				.countSelect();

		return this.json(data);
	}


	// 停用、启用产品
	async goodsstatusAction(){
		// 暂时只停用分店
		let id = this.post('id');
		let st = this.post('st');
		let shopid = this.shop_userinfo.departmentid

		let res = await this.model('or_shop_goods').where({goodsid:id, shopid: shopid}).update({isdisable:st});
		if (st*1) {
			return res?this.success('停用成功'):this.fail('停用失败');
		} else {
			return res?this.success('启用成功'):this.fail('启用失败');
		}
	}




}